import instance from '../instance.js'

// 文件相关API
export const fileAPI = {
    // 上传用户头像
    uploadUserAvatar(file) {
        const formData = new FormData()
        formData.append('file', file)

        return instance.post('/file/user-avatar', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
    },

    // 上传店铺logo
    uploadShopLogo(file) {
        const formData = new FormData()
        formData.append('file', file)

        return instance.post('/file/shop-logo', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
    },

    // 上传商品图片
  uploadProductImage(productId, file) {
    // 确保文件对象存在且有效
    if (!file) {
      console.error('uploadProductImage: file is null or undefined')
      throw new Error('文件对象无效')
    }
    
    // 创建FormData对象
    const formData = new FormData()
    formData.append('productId', productId)
    
    // 确保文件是Blob类型
    let fileToUpload = file
    if (!(file instanceof Blob)) {
      console.warn('文件不是Blob类型，尝试转换')
      if (file instanceof File) {
        fileToUpload = file
      } else if (file.file) {
        fileToUpload = file.file
      } else {
        throw new Error('无法识别的文件类型')
      }
    }
    
    // 添加文件到FormData
    formData.append('file', fileToUpload)
    
    // 确保文件名正确传递
    const fileName = file.name || fileToUpload.name || ('product_image_' + Date.now() + '.jpg')
    formData.append('fileName', fileName)
    for (let [key, value] of formData.entries()) {
      console.log(`  ${key}:`, value, typeof value)
    }

    return instance.post('/file/product-image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      transformRequest: [function (data) {
        // 对于FormData，不要转换数据
        return data
      }]
    })
  }
}

export default fileAPI